import config from "./config.js";
import {
	nativeUI,
	saveClosePage
} from '@/utils/index.js'
import local from '@/utils/localStorage.js'; //引入本地存储方法
/* 
		@parms url 接口地址
		@parms method 请求方式
		@parms data 参数
		@parms isUpload 默认false 是否上传
 */

const request = (url, method, data, isUpload = false, name = 'img') => {
	return new Promise((resolve, reject) => {
		if (!isUpload) {
			uni.request({
				url: config.baseURL + url, //仅为示例，并非真实接口地址。
				data: data,
				method: method,
				timeout: config.timeout,
				header: {
					'Content-Type': 'application/x-www-form-urlencoded',
					// 'Content-Type': 'application/json; charset=utf-8',
					// 'token': local.get('token') || '', //登录凭证
					'Authorization': local.get('token') || '', //登录凭证
					'UserAuth': 'user'
				},
				success: (res) => { //具体捕获请看自己接口返回的形式
					if (res.data.code == 0 || res.data.code == 106) {
						resolve(res.data)
					} else if (res.data.code == 1009 || res.data.code == 1008) {
						uni.$emit('updatelogin')
						// local.remove('token')
						// setTimeout(() => {
						// 	uni.$uv.route({
						// 		type: 'redirect',
						// 		url: '/pages/Login/login/login'
						// 	})
						// 	// 保存页面失效当前路径
						// 	saveClosePage()
						// }, 1000)
						// nativeUI('登录状态失效')

					} else {
						nativeUI(res.data.msg)
					}
				},
				fail(error) {
					console.error(error);
					reject(error)
				},
			});
		} else {
			uni.uploadFile({
				url: config.baseURL + url,
				filePath: data,
				name,
				header: {
					// 'token': local.get('token') || '', //登录凭证
					'Authorization': local.get('token') || '', //登录凭证
				},
				formData: {
					type: 1
				},
				fileType: 'image',
				success: (uploadFileRes) => {
					console.error(uploadFileRes);
					let parms = JSON.parse(uploadFileRes.data)

					if (parms.code == 200 || parms.code == 1 || parms.code == 0) {
						resolve(parms)
					} else {

						nativeUI(parms.msg)
					}
				},
				fail: (e) => {
					console.log(e);
					nativeUI('上传失败')
				}
			});
		}

	})
}

export default {
	request //向外暴露request
}